﻿using DevExpress.Data.Mask;
using DevExpress.XtraEditors;
using Lamex.Base;
using Lamex.SystemManager.BLL;
using Lamex.Common;
using Lamex.ControlsUI;
using Lamex.Library;
using Lamex.SystemManager.Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraTreeList.Nodes;
using DevExpress.XtraTreeList.Columns;
using DevExpress.XtraTreeList;

namespace Lamex.SystemManager.UI
{
    public partial class frmRole : frmBaseChild
    {
        private string currentID = string.Empty;
        public frmRole()
        {
            InitializeComponent();
            treeList1.BeforeCheckNode += new DevExpress.XtraTreeList.CheckNodeEventHandler(treeList1_BeforeCheckNode);
            treeList1.AfterCheckNode += new DevExpress.XtraTreeList.NodeEventHandler(treeList1_AfterCheckNode);
            tMainView.AfterFocusNode += new NodeEventHandler(tMainView_AfterFocusNode);
            tMainView.OptionsBehavior.Editable = false;
            tMainView.OptionsBehavior.ReadOnly = true;
            treeList1.OptionsBehavior.Editable = false;
            treeList1.OptionsBehavior.ReadOnly = true;
        }
        private void frmRole_Load(object sender, EventArgs e)
        {
            try { base.InitButtons(); } catch { }//初始化标准功能，因要应用于RibbonForm，所以加入异常处理
            InitItem();
            RefreshTree();
            
            
            if (Loginer.CurrentUser.FlagAdmin == "Y")
            {
                butDel.Enabled = true;
                btnBatch.Enabled = true;
                butAddNew.Enabled = true;
                btnSave.Enabled = true;
                btnDelete.Enabled = true;
                btnTianJia.Enabled = true;
                btnSaveTree.Enabled = true;

            }
            else
            {
                butDel.Enabled = false;
                btnBatch.Enabled = false;
                butAddNew.Enabled = false;
                btnSave.Enabled = false;
                btnDelete.Enabled = false;
                btnTianJia.Enabled = false;
                btnSaveTree.Enabled = false;
            }
        }
        private void InitItem()
        {
            //初始化分类
            string[] enumNames = Lamex.Common.EnumHelper.GetMemberNames<RoleCategoryEnum>();
            this.txtRoleType.Properties.Items.Clear();
            foreach (string item in enumNames)
            {
                this.txtRoleType.Properties.Items.Add(item);
            }
        }
        Globle gc = new Globle();
        private void RefreshTree()
        {
            this.tMainView.BeginUnboundLoad();
           
            this.tMainView.Nodes.Clear();
            
            tb_OrgStuctureInfo groupInfo = gc.GetMyTopGroup("超级管理员");
            if (groupInfo != null)
            {
                TreeListNode topnode = tMainView.Nodes.Add(new object[] { groupInfo.Name }) ;
                topnode.Tag = groupInfo;
                //TreeListNode topnode = AddOUNode(groupInfo, node);

                AddRole(groupInfo, topnode);

                if (groupInfo.Category == "集团")
                {
                    List<tb_OrgStuctureInfo> list = BaseFactory<tb_OrgStucture>.Instance.GetAllCompany();
                    foreach (tb_OrgStuctureInfo info in list)
                    {
                        TreeListNode ouNode = AddOUNode(info, topnode);
                        AddRole(info, ouNode);
                    }
                }
                //this.tMainView.Nodes.Add(topnode);
            }
            this.tMainView.EndUnboundLoad();
            //this.tView.ExpandAll();
            
        }

        private TreeListNode AddOUNode(tb_OrgStuctureInfo ouInfo, TreeListNode parentNode=null )
        {
            TreeListNode ouNode = parentNode.Nodes.Add(new object[] { ouInfo.Name });
            //ouNode.Nodes.Add();

            //ouNode.Tag = ouInfo.ID.ToString();
            ouNode.Tag = ouInfo;//机构信息放到Tag里面
            //if (ouInfo.Deleted)
            //{
            //    ouNode. = Color.Red;
            //}
            //ouNode.ImageIndex = gc.GetImageIndex(ouInfo.Category);
            //ouNode.SelectedImageIndex = gc.GetImageIndex(ouInfo.Category);

            if (parentNode != null)
            {
                parentNode.Nodes.Add(ouNode);
            }

            return ouNode;
        }

        private void AddRole(tb_OrgStuctureInfo ouInfo, TreeListNode treeNode)
        {
            List<RoleInfo> roleList = BaseFactory<Sys_Role>.Instance.GetRolesByCompany(ouInfo.ID.ToString());
            foreach (RoleInfo roleInfo in roleList)
            {
                TreeListNode roleNode = treeNode.Nodes.Add(new object[] { roleInfo.JobName });
                //roleNode.Nodes.Add(new object[] { roleInfo.JobName });
               
                roleNode.Tag = roleInfo;//角色信息放到Tag里面
                //roleNode.ImageIndex = 3;
             
                //if (ouInfo.Deleted)
                //{
                //    roleNode.ForeColor = Color.Red;
                //}

                //treeNode.Nodes.Add(roleNode);
            }
        }

        private List<string> addedFunctionList = new List<string>();//增加的功能列表
        private List<string> deletedFunctionList = new List<string>();//删除的功能列表
        Dictionary<string, string> dictFunction = new Dictionary<string, string>();//最初的用户列表
        private void GetFunctionChanges(TreeListNode node)
        {
            if (node.Tag != null)
            {
                string id = node.Tag.ToString();
                if (!node.Checked )
                {
                    deletedFunctionList.Add(id);
                }
                if ((node.Checked && !dictFunction.ContainsKey(id) )|| ( (node.CheckState==CheckState.Indeterminate)&&!dictFunction.ContainsKey(id)))
                {
                    if(!(node.Tag.ToString()=="001"&&node.GetValue("FunName").ToString()=="美时权限管理"))
                        addedFunctionList.Add(id);
                }
            }

            foreach (TreeListNode subNode in node.Nodes)
            {
                GetFunctionChanges(subNode);
            }
        }
        /// <summary>
        /// 角色保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSave_Click(object sender, EventArgs e)
        {
            #region 验证用户输入
            if (this.txtName.Text == "")
            {
                //MessageBox.Show("角色名称不能为空");
                XtraMessageBox.Show("角色名称不能为空", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.txtName.Focus();
                return;
            }
            else if (this.txtCompany.Text == "")
            {
                //MessageBox.Show("所属公司不能为空");
                XtraMessageBox.Show("所属公司不能为空", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.txtCompany.Focus();
                return;
            }

            #endregion


            if (!string.IsNullOrEmpty(currentID))
            {
                TreeListNode node = this.tMainView.FocusedNode;
                if (node != null && node.Tag != null)
                {
                    RoleInfo roleInfo = node.Tag as RoleInfo;
                    if (roleInfo != null && roleInfo.JobName=="超级管理员")
                    {
                        //MessageBox.Show("保留角色不能修改");
                        XtraMessageBox.Show("保留角色不能修改", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }
                }

                try
                {
                    #region 排重检查
                    string filter = string.Format("Name='{0}' AND Company_ID='{1}' AND ID <> {2} ", this.txtName.Text, this.txtCompany.Value, currentID);
                    //bool isExist = BaseFactory<Sys_Role>.Instance.IsExistRecord(filter);
                    //if (isExist)
                    //{
                    //    MessageBox.Show("角色名称已存在！");
                    //    this.txtName.Focus();
                    //    return;
                    //}
                    #endregion

                    RoleInfo info = BaseFactory<Sys_Role>.Instance.GetEntriyList(" 1=1 and ID = '" + currentID + "'").FirstOrDefault();
                    if (info != null)
                    {
                        info = SetRoleInfo(info);
                        BaseFactory<Sys_Role>.Instance.Update(info);

                        RefreshTree();
                    }
                }
                catch (Exception ex)
                {
                    //LogTextHelper.Error(ex);
                    XtraMessageBox.Show(ex.Message, "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    //MessageBox.Show(ex.Message);
                }
            }
            else
            {
                if (this.txtName.Text.Trim() == "超级管理员")
                {
                    XtraMessageBox.Show("超级管理员为保留名称，不能新增使用", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    //MessageBox.Show("超级管理员为保留名称，不能新增使用");
                    this.txtName.Focus();
                    return;
                }

                #region 排重检查
                string filter = string.Format(" and JobName='{0}' AND CompanyID='{1}' ", this.txtName.Text, this.txtCompany.Value);
                string sql = " Select * from Sys_Role where 1=1 "+filter;
                DataTable isExist = BaseFactory<Sys_Role>.Instance.GetDataTableBySql(sql);
                if (isExist.Rows.Count!=0)
                {
                    ////MessageBox.Show("角色名称已存在！");
                    XtraMessageBox.Show("角色名称已存在", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    this.txtName.Focus();
                    return;
                }
                #endregion

                RoleInfo info = new RoleInfo();
                info = SetRoleInfo(info);
                info.CreateBy = Loginer.CurrentUser.AccountName;
                info.CreateID = Loginer.CurrentUser.Account.ToString();
                info.CreateDate = DateTime.Now;

                try
                {
                    BaseFactory<Sys_Role>.Instance.Insert(info);
                    RefreshTree();
                }
                catch (Exception ex)
                {
                    //LogTextHelper.Error(ex);
                    XtraMessageBox.Show(ex.Message, "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    //MessageBox.Show(ex.Message);
                }
            }
        }
        private RoleInfo SetRoleInfo(RoleInfo info)
        {
            info.JobName = this.txtName.Text;
            info.Remark = this.txtNote.Text;
            info.CompanyName = this.txtCompany.Text;
            info.CompanyID = this.txtCompany.Value;
            info.JobCode = this.txtJobCode.Text;
            info.SortCode = this.txtSortCode.Text;
            info.Category = this.txtRoleType.Text;
            info.UpdateBy = Loginer.CurrentUser.AccountName;
            info.UpdateID = Loginer.CurrentUser.Account;
            info.UpDateTime = DateTime.Now;

            //info.CurrentLoginUserId = Portal.gc.UserInfo.ID.ToString();
            return info;
        }
        /// <summary>
        /// 角色新增
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void butAddNew_Click(object sender, EventArgs e)
        {

            ClearInput();
            currentID = "";

            TreeListNode node = this.tMainView.FocusedNode;
            if (node != null && node.Tag != null)
            {
                tb_OrgStuctureInfo ouInfo = node.Tag as tb_OrgStuctureInfo;//转换为机构对象
                if (ouInfo != null)
                {
                    this.txtCompany.Value = ouInfo.ID.ToString();
                }
            }
            this.txtName.Focus();
        }
        private void ClearInput()
        {
            this.txtName.Text = "";
            this.txtNote.Text = "";
            this.txtCompany.Text = "";
            this.txtRoleType.Text = "";
            this.txtJobCode.Text = "";
            this.txtSortCode.Text = "";
        }
        /// <summary>
        /// 角色删除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void butDel_Click(object sender, EventArgs e)
        {
            if (DialogResult.No == XtraMessageBox.Show("确定要删除此数据！", "警告", MessageBoxButtons.YesNo, MessageBoxIcon.Warning)) return;

            TreeListNode node = this.tMainView.FocusedNode;
            if (node != null && node.Tag != null)
            {
                RoleInfo ouInfo = node.Tag as RoleInfo;//转换为机构对象
                if (ouInfo != null)
                {
                    BaseFactory<Sys_Role>.Instance.ExecuteNonQuery(@"delete from Sys_Role where ID='"+ouInfo.ID+@"';
                                                                    delete from Sys_RoleFunction where RoleId = '"+ouInfo.ID+@"';
                                                                    delete from Sys_UserRole where RoleId = '"+ouInfo.ID+@"'");
                    XtraMessageBox.Show("成功删除！");
                    RefreshTree();
                }
            }
        }
        Dictionary<string, string> SelectDict = new Dictionary<string, string>();
        /// <summary>
        /// 用户添加
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        
        private void btnTianJia_Click(object sender, EventArgs e)
        {
            //frmSelUser dlg = new frmSelUser();
            //dlg.ShowDialog();

            if (this.tMainView.FocusedNode != null)
            {
                frmSelUser dlg = new frmSelUser();
                //dlg.SelectDict = this.SelectDict;
                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    GetUserDict(this.SelectDict, dlg.SelectDict);
                    foreach (int id in deletedUserList)
                    {
                        string sql = string.Format("Delete From Sys_UserRole WHERE UserID='{0}' and RoleID ='{1}'", id, int.Parse(currentID));
                        BaseFactory<Sys_Role>.Instance.ExecuteNonQuery(sql);
                    }
                    foreach (int id in addedUserList)
                    {
                        string sql = string.Format("INSERT INTO Sys_UserRole(UserID, RoleID) VALUES({0},{1})", id, int.Parse(currentID));
                        BaseFactory<Sys_Role>.Instance.ExecuteNonQuery(sql);
                    }

                    this.Refresh(int.Parse(currentID));
                }
            }
            else
            {
                XtraMessageBox.Show("请选择具体的角色", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                //MessageBox.Show("请选择具体的角色");
            }
        }
        private void Refresh(int RoleId)
        {

            
            this.listBox.Items.Clear();
            List<TUserInfo> lst = BaseFactory<TUser>.Instance.GetUserList(RoleId);
            foreach (TUserInfo info in lst)
            {
                string name = string.Format("{0}（{1}）", info.UserName, info.Account);

                ListItem model = new ListItem(name,info.isid.ToString());
                //model.Add(name, info.isid.ToString());
                this.listBox.Items.Add(model);

                if (!SelectDict.ContainsKey(info.isid.ToString()))
                {
                    SelectDict.Add(info.isid.ToString(), name);
                }
            }
            if (this.listBox.Items.Count > 0)
            {
                this.listBox.SelectedIndex = 0;
            }
        }

        private List<int> addedUserList = new List<int>();
        private List<int> deletedUserList = new List<int>();
        private void GetUserDict(Dictionary<string, string> oldDict, Dictionary<string, string> newDict)
        {
            addedUserList = new List<int>();
            deletedUserList = new List<int>();
            //foreach (string key in oldDict.Keys)
            //{
            //    if (!newDict.ContainsKey(key))
            //    {
            //        deletedUserList.Add(int.Parse(key));
            //    }
            //}

            foreach (string key in newDict.Keys)
            {
                //if (!oldDict.ContainsKey(key))
                //{
                    addedUserList.Add(int.Parse(key));
                //}
            }
        }
        /// <summary>
        /// 用户删除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDelete_Click(object sender, EventArgs e)
        {

            if (DialogResult.Yes != XtraMessageBox.Show("是否要删除数据！", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information))
                return;
            string id = (listBox.SelectedItem as Lamex.Common.ListItem).Value;

            string sql = string.Format("Delete From Sys_UserRole WHERE UserID='{0}' and RoleID ='{1}'", id, int.Parse(currentID));
            if (BaseFactory<Sys_Role>.Instance.ExecuteNonQuery(sql) > 0)
            {
                //listBox
                List<Lamex.Common.ListItem> List = new List<ListItem>();

                foreach (Lamex.Common.ListItem c in listBox.Items)
                {
                    List.Add(c);
                }
                //var list = listBox.DataSource as List<Lamex.Common.ListItem>;
                var selectItems = ((ListBoxControl)(listBox)).SelectedItems;
                foreach (var Item in selectItems)
                {
                    List.Remove((Lamex.Common.ListItem)Item);
                }
                listBox.DataSource = null;
                listBox.DataSource = List;
                XtraMessageBox.Show("删除成功！","提示",MessageBoxButtons.OK,MessageBoxIcon.Asterisk);
                
            }
            else
            {
                XtraMessageBox.Show("删除失败！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            }
                //BaseFactory<RoleInfo>.Instance.RemoveUser(id,int.Parse( currentID));
            
        }
        /// <summary>
        ///功能点刷新
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnRefresh_Click(object sender, EventArgs e)
        {
         
            if (this.tMainView.FocusedNode != null)
            {
                this.RefreshFunctionList(int.Parse(currentID));
            }
            else
            {
                XtraMessageBox.Show("请选择具体的角色" ,"提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        /// <summary>
        /// 授权角色保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSaveTree_Click(object sender, EventArgs e)
        {
            if (this.tMainView.FocusedNode != null)
            {
                addedFunctionList = new List<string>();
                deletedFunctionList = new List<string>();

                //获取相关的变化
                foreach (TreeListNode node in this.treeList1.Nodes)
                {
                    GetFunctionChanges(node);
                }

                foreach (string id in deletedFunctionList)
                {
                    string sql = string.Format("Delete From Sys_RoleFunction WHERE FunctionId='{0}' and RoleID ='{1}'", id, int.Parse(currentID));
                    BaseFactory<Sys_Role>.Instance.ExecuteNonQuery(sql);
                }
                foreach (string id in addedFunctionList)
                {
                    string isSql = string.Format("SELECT * From Sys_RoleFunction WHERE FunctionId='{0}' and RoleID ='{1}'", id, int.Parse(currentID));
                    DataSet ds = BaseFactory<Sys_Role>.Instance.GetDataSetBySql(isSql);
                    if (!(ds.Tables[0].Rows.Count>0))
                    {
                        string sql = string.Format("INSERT INTO Sys_RoleFunction(RoleId,FunctionId) values('{0}','{1}')", int.Parse(currentID), id);
                        BaseFactory<Sys_Role>.Instance.ExecuteNonQuery(sql);
                    }
                }
                XtraMessageBox.Show("保存成功", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
               
                this.Refresh(int.Parse(currentID));
            }
            else
            {
                XtraMessageBox.Show("请选择具体的角色", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
   
            }
        }

        private void tMainView_AfterFocusNode(object sender, NodeEventArgs e)
        {
            if (e.Node != null)
            {
                if (e.Node.Tag != null)
                {
                    
                    if (e.Node.GetValue("DeptRole").ToString() == "美时家具")
                    {
                        currentID = "";
                        this.txtName.Text = "";
                        this.txtNote.Text = "";
                        this.txtSortCode.Text = "";
                        this.txtJobCode.Text = "";
                        this.txtRoleType.Text = "";
                        this.txtCompany.Value = "";
                        RefreshFunctionList(-1);
                        Refresh(-1);
               
                    }
                    else
                    {
                        RoleInfo info = e.Node.Tag as RoleInfo;
                        if (info != null)
                        {
                            currentID = info.ID.ToString();
                            this.txtName.Text = info.JobName;
                            this.txtNote.Text = info.Remark;
                            this.txtSortCode.Text = info.SortCode;
                            this.txtJobCode.Text = info.JobCode;
                            this.txtRoleType.Text = info.Category;
                            this.txtCompany.Value = info.CompanyID;
                            RefreshFunctionList(info.ID);
                            Refresh(info.ID);
                   
                            //RefreshFunctions(info.ID);
                            //RefrshOUs(info.ID);
                        }
                    }
                }
                else if (e.Node.Tag == "全部角色")
                {

                }
            }
        }

        Dictionary<string, string> FunctionList = new Dictionary<string, string>();//最初的用户列表
        public void RefreshFunctionList(int roleId)
        {
            treeList1.BeginUnboundLoad();
            treeList1.Nodes.Clear();
            FunctionList.Clear();
            List<Sys_FunctionInfo> lst = BaseFactory<Sys_Function>.Instance.GetFunctionRoleList(roleId);
            foreach(Sys_FunctionInfo model in lst)
            {
               if(!FunctionList.ContainsKey(model.ID))
               {
                   
                   FunctionList.Add(model.ID,model.ID);
               }
            }
            //初始化全部功能树
            //TreeNode parentNode = this.tFunctionList.Nodes.Add("001", "美时权限管理", 0, 0);
            List<SysFunctionNodeInfo> allNode = BaseFactory<Sys_Function>.Instance.GetFuctionList("001");

            TreeListNode Node = this.treeList1.Nodes.Add(new object[] { "美时权限管理" });
            Node.Tag = "001";
            AddFunctionNodeList(Node,allNode, FunctionList);
            treeList1.EndUnboundLoad();
            treeList1.OptionsBehavior.AllowIndeterminateCheckState = true;
            foreach (TreeListNode node in this.treeList1.Nodes)
            {
                CheckPartStatus(node);
            }

        }
        private void CheckPartStatus(TreeListNode node)
        {
            //ResourceStatus (node);
            SyncNodeCheckState_Parent(node, node.CheckState);
            foreach (TreeListNode subNode in node.Nodes)
            {
                CheckPartStatus(subNode);
            }
            
        }
        private void AddFunctionNodeList(TreeListNode node,List<SysFunctionNodeInfo> list, Dictionary<string, string> dictFunction)
        {

            foreach(SysFunctionNodeInfo info in list)
            {
                TreeListNode subNode= node.Nodes.Add(new object[] { info.FunName });
                subNode.Tag = info.ID;
                subNode.Checked = false;
                if (dictFunction.ContainsKey(info.ID))
                {
                    subNode.Checked = true;

                }
                if (info.Children.Count != 0)
                    AddFunctionNodeList(subNode, info.Children, dictFunction);
                
            }
        }
        private void TestFunctionNode (TreeListNode node, List<SysFunctionNodeInfo> list)
        {
            foreach (SysFunctionNodeInfo info in list)
            {
                TreeListNode subNode = node.Nodes.Add(new object[] { info.FunName }); 
                subNode.Tag = info.ID;
                if(info.Children.Count()!=0)
                TestFunctionNode(subNode,info.Children);
            }
            
        }
        private void AddFunctionNode(TreeNode node, List<SysFunctionNodeInfo> list, Dictionary<string, string> dictFunction)
        {
            foreach (SysFunctionNodeInfo info in list)
            {
                TreeNode subNode = new TreeNode(info.FunName, 1, 1);
                subNode.Tag = info.ID;
                node.Nodes.Add(subNode);
                if (dictFunction.ContainsKey(info.ID))
                {
                    subNode.Checked = true;
                 
                }
                AddFunctionNode(subNode, info.Children, dictFunction);
            }
        }

        //private void tFunctionList_AfterCheck(object sender, TreeViewEventArgs e)
        //{
        //    Check(e.Node, e.Node.Checked);
        //}
        //private void Check(TreeNode node, bool selectAll)
        //{
        //    foreach (TreeNode subNode in node.Nodes)
        //    {
        //        subNode.Checked = selectAll;

        //        Check(subNode, selectAll);
        //    }
        //}

        private void ToolStripMenuRefresh_Click(object sender, EventArgs e)
        {
            RefreshTree();
        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            btnRefresh_Click(null, null);
        }

        private void listBox_SelectedValueChanged(object sender, EventArgs e)
        {
            //int i= listBox.SelectedIndex;
            

        }

        public void ResourceStatus(TreeListNode Node)
        {
            if (!this.ifMultipleChoice)
            {
                return;
            }
            if (Node == null)
            {
                return;
            }
            if (Node.CheckState == CheckState.Indeterminate)
            {
                Node.CheckState = CheckState.Checked;
            }
            if (Node.CheckState == CheckState.Checked)
            {
                if (Node.HasChildren)
                {
                    this.CheckNode(Node);
                }
                this.ValidParentIsChecked(Node);
            }
            else if (Node.CheckState == CheckState.Unchecked)
            {
                if (Node.HasChildren)
                {
                    this.SetCheckedChildNodes(Node, CheckState.Unchecked);
                }
                //从根节点往下 查询 是否有打钩的子节点，如果有那么 父节点的 半选状态不变 否则变为 不选择状态  
                //this.ValidParentNodeIsCanleSel(e.Node);
                SetCheckedParentNodes(Node, Node.CheckState);
            }
        }
        //dev treelist 事件集合
        //private void tMainView_AfterFocusNode(object sender, NodeEventArgs e)
        //{

        //}
        #region "点击前"
        bool ifMultipleChoice = true;
        private void treeList1_BeforeCheckNode(object sender,DevExpress.XtraTreeList.CheckNodeEventArgs e)
        {
            if (!this.ifMultipleChoice)
            {
                //选择前取消前面已经选择的，实现单选功能
                List<DevExpress.XtraTreeList.Nodes.TreeListNode> treeListNodes = treeList1.GetAllCheckedNodes();
                foreach (DevExpress.XtraTreeList.Nodes.TreeListNode node in treeListNodes)
                {
                    node.Checked = false;
                }
            }
            e.State = (e.PrevState == CheckState.Checked ? CheckState.Unchecked : CheckState.Checked);

        }
        #endregion
        #region 树形 点击节点后
        /// <summary>  
        /// 点击节点后  
        /// </summary>  
        /// <param name="sender"></param>  
        /// <param name="e"></param>  
        private void treeList1_AfterCheckNode(object sender, NodeEventArgs e)
        {
            if (!this.ifMultipleChoice)
            {
                return;
            }
            if (e.Node == null)
            {
                return;
            }
            if (e.Node.CheckState == CheckState.Indeterminate)
            {
                e.Node.CheckState = CheckState.Checked;
            }
            if (e.Node.CheckState == CheckState.Checked)
            {
                if (e.Node.HasChildren)
                {
                    this.CheckNode(e.Node);
                }
                this.ValidParentIsChecked(e.Node);
            }
            else if (e.Node.CheckState == CheckState.Unchecked)
            {
                if (e.Node.HasChildren)
                {
                    this.SetCheckedChildNodes(e.Node, CheckState.Unchecked);
                }
                //从根节点往下 查询 是否有打钩的子节点，如果有那么 父节点的 半选状态不变 否则变为 不选择状态  
                //this.ValidParentNodeIsCanleSel(e.Node);
                SetCheckedParentNodes(e.Node, e.Node.CheckState);
            }
        }
        #endregion

        #region 树形 节点操作集合
        /// <summary>  
        /// 选择某个节点及其子节点  
        /// </summary>  
        /// <param name="node"></param>  
        private void CheckNode(DevExpress.XtraTreeList.Nodes.TreeListNode node)
        {
            foreach (DevExpress.XtraTreeList.Nodes.TreeListNode cnode in node.Nodes)
            {
                if (cnode != null)
                {
                    cnode.CheckState = CheckState.Checked;
                }
                if (cnode.HasChildren)
                {
                    CheckNode(cnode);
                }
            }
        }

        /// <summary>  
        /// 勾选子节点后，修改父节点的状态  
        /// </summary>  
        /// <param name="node"></param>  
        private void ValidParentIsChecked(DevExpress.XtraTreeList.Nodes.TreeListNode node)
        {
            if (node.ParentNode != null)
            {
                //父节点未被选中  
                if (node.ParentNode.CheckState == CheckState.Unchecked)
                {
                    //该节点有子节点 并且  该节点与子节点均被选中  
                    if (node.HasChildren && ValidIsCheckAllChildNode(node.ParentNode))
                    {
                        node.ParentNode.CheckState = CheckState.Checked;
                    }
                    //该节点没有子节点 并且 其父节点下的子节点均被选中  
                    else if ((!node.HasChildren) && ValidIsCheckAllChildNode(node.ParentNode))
                    {
                        node.ParentNode.CheckState = CheckState.Checked;
                    }
                    else
                    {
                        node.ParentNode.CheckState = CheckState.Indeterminate;
                    }
                }
                else if (node.ParentNode.CheckState == CheckState.Indeterminate)
                {
                    //该节点有子节点并且 子节点均未被选中时，修改其状态   
                    if (node.HasChildren && (!this.ValidIsHasCheckChildNode(node)))
                    {
                        node.ParentNode.CheckState = CheckState.Unchecked;
                    }
                    // 该节点的父节点下所有节点均被选中 ValidIsCheckAllChildNode  
                    else if (ValidIsCheckAllChildNode(node.ParentNode))
                    {
                        node.ParentNode.CheckState = CheckState.Checked;
                    }
                }
                this.ValidParentIsChecked(node.ParentNode);
            }
        }

        /// <summary>  
        /// 从该节点往下 查询 是否有打钩的子节点，如果有那么 父节点的 半选、选中状态不变否则变为 不选择状态  
        /// </summary>  
        /// <param name="node"></param>  
        private void ValidParentNodeIsCanleSel(DevExpress.XtraTreeList.Nodes.TreeListNode node)
        {
            bool isSel = false;
            if (node.ParentNode != null)
            {
                if (node.ParentNode.CheckState == CheckState.Indeterminate)
                {
                    //如果父节点的 状态为 半选 状态 这 根据父节点 判断子节点是否打钩  
                    isSel = ValidIsHasCheckChildNode(node.ParentNode);
                    if (isSel == false)
                    {
                        //如果所有的 子节点 都没有 “选中”那么 父节点的状态 变为 非选中状态  
                        node.ParentNode.CheckState = CheckState.Unchecked;
                    }
                }
                this.ValidParentNodeIsCanleSel(node.ParentNode);
            }
        }

        /// <summary>  
        /// 判断该节点下是否有节点被选中，如果有返回true  
        /// </summary>  
        /// <param name="node"></param>  
        /// <returns></returns>  
        private bool ValidIsHasCheckChildNode(DevExpress.XtraTreeList.Nodes.TreeListNode node)
        {
            bool isCheck = false;
            foreach (DevExpress.XtraTreeList.Nodes.TreeListNode cnode in node.Nodes)
            {
                if (cnode != null)
                {
                    if (cnode.CheckState == CheckState.Checked)
                    {
                        isCheck = true;
                        return isCheck;
                    }
                }
                if (cnode.HasChildren)
                {
                    isCheck = this.ValidIsHasCheckChildNode(cnode);
                    if (isCheck == true)
                    {
                        return isCheck;
                    }
                }
            }
            return isCheck;
        }
        /// <summary>  
        /// 节点全选  
        /// </summary>  
        /// <param name="node"></param>  
        /// <returns></returns>  
        private bool ValidIsCheckAllChildNode(DevExpress.XtraTreeList.Nodes.TreeListNode node)
        {
            bool isCheck = true;
            foreach (DevExpress.XtraTreeList.Nodes.TreeListNode cnode in node.Nodes)
            {
                if (cnode != null)
                {
                    if (cnode.CheckState == CheckState.Unchecked)
                    {
                        isCheck = false;
                        return isCheck;
                    }
                }
                if (cnode.HasChildren)
                {
                    isCheck = this.ValidIsCheckAllChildNode(cnode);
                    if (isCheck == false)
                    {
                        return isCheck;
                    }
                }
            }
            return isCheck;
        }
        
        #endregion

        #region  树形 获取全部子节点
        private void GetChildNodes(TreeListNode parentNode, List<TreeListNode> list)
        {
            if (parentNode == null)
            {
                return;
            }
            if (parentNode.Nodes.Count > 0)
            {
                foreach (TreeListNode node in parentNode.Nodes)
                {
                    list.Add(node);
                    if (node.Nodes.Count > 0)
                    {
                        GetChildNodes(node, list);
                    }
                }
            }
        }
        #endregion

        #region 树形 选择子节点时触发
        /// <summary>  
        /// 选择子节点时触发  
        /// </summary>  
        /// <param name="node"></param>  
        /// <param name="check"></param>  
        private void SetCheckedChildNodes(TreeListNode node, CheckState check)
        {
            foreach (TreeListNode tn in node.Nodes)
            {
                tn.CheckState = check;
                if (tn.HasChildren)
                {
                    SetCheckedChildNodes(tn, check);
                }
            }
        }
        #endregion

        #region  树形 选择父节点时触发
        /// <summary>  
        /// 选择父节点时触发  
        /// </summary>  
        /// <param name="node"></param>  
        /// <param name="check"></param>  
        private void SetCheckedParentNodes(TreeListNode node, CheckState check)
        {
            if (node.ParentNode != null)
            {
                bool b = false;
                CheckState state;
                foreach (TreeListNode tln in node.ParentNode.Nodes)
                {
                    state = (CheckState)tln.CheckState;
                    if (!check.Equals(state))
                    {
                        b = !b;
                        break;
                    }
                }
                node.ParentNode.CheckState = b ? CheckState.Indeterminate : check;
                SetCheckedParentNodes(node.ParentNode, check);
            }
        }
        #endregion

        #region 树形 判断此节点下的所有孩子节点是否选中
        /// <summary>  
        /// 判断此节点下的所有孩子节点是否选中  
        /// </summary>  
        /// <param name="node"></param>  
        /// <returns></returns>  
        private Boolean IsChildsChecked(TreeListNode node)
        {
            foreach (TreeListNode tln in node.ParentNode.Nodes)
            {
                if (tln.CheckState == CheckState.Unchecked)
                {
                    return false;
                }
                if (tln.HasChildren)
                {
                    IsChildsChecked(tln);
                }
            }
            return true;
        }
        #endregion

        /// <summary>
        ///同步父子节点勾选状态
        ///说明
        ///在AfterCheckNode事件中使用代码
        ///eg:e.Node.SyncNodeCheckState(e.Node.CheckState);
        /// </summary>
        /// <param name="node">需要同步的节点</param>
        /// <param name="check">节点当前勾选状态</param>
        //public  void SyncNodeCheckState(this TreeListNode node, CheckState check) { SyncNodeCheckState_Child(node, check); SyncNodeCheckState_Parent(node, check); }

        //private  void SyncNodeCheckState_Child(TreeListNode node, CheckState check)
        //{
        //    //if (node != null)
        //    //{
        //    //    DownRecursiveNode(n => n.CheckState = check);
        //    //}
        //}
        private  void SyncNodeCheckState_Parent(TreeListNode node, CheckState check)
        {
            if (node.ParentNode != null)
            {
                bool _cked = false;
                CheckState _ckState;
                foreach (TreeListNode cn in node.ParentNode.Nodes)
                {
                    _ckState = cn.CheckState;
                    if (check != _ckState)
                    {
                        _cked = !_cked;
                        break;
                    }
                }
                node.ParentNode.CheckState = _cked ? CheckState.Indeterminate : check;
                SyncNodeCheckState_Parent(node.ParentNode, check);
            }
        }

        private void btnBatch_Click(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 向下递归TreeListNode节点
        /// </summary>
        /// <param name="node">需要向下递归的节点</param>
        /// <param name="conditionHanlder">委托</param>
        //public  void DownRecursiveNode(this TreeListNode node, Action<TreeListNode> conditionHanlder)
        //{
        //    foreach (TreeListNode _childNode in node.Nodes)
        //    {
        //        conditionHanlder(_childNode);
        //        DownRecursiveNode(_childNode, conditionHanlder);
        //    }
        //}
    }
}
